package com.luotao.test.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * User: luotao
 * Date: 12-5-4
 * Time: 11:19:00
 */
public class ConnectAsync {
    public static void main(String[] argv) throws Exception {
        String host = "localhost";
        int port = 8080;
        if (argv.length == 2) {
            host = argv[0];
            port = Integer.parseInt(argv[1]);
        }
        InetSocketAddress addr = new InetSocketAddress(host, port);
        SocketChannel sc = SocketChannel.open();
        sc.configureBlocking(false);
        System.out.println("initiating connection");
        sc.connect(addr);
        while (!sc.finishConnect()) {
            doSomethingUseful();
        }
        System.out.println("connection established"); // Do something with the connected socket
        // // The SocketChannel is still nonblocking
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        byteBuffer.put("hello".getBytes());
        sc.write(byteBuffer);
//        ByteBuffer byteBuffer = ByteBuffer.allocate(100);
//        sc.read(byteBuffer);
//        System.out.println("new String(byteBuffer.array()) = " + new String(byteBuffer.array()));
//        sc.close();
    }

    private static void doSomethingUseful() {
        System.out.println("doing something useless");
    }
}
